package com.benshou.bsoa.common.trace;

import org.jetbrains.annotations.NotNull;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

import java.util.Map;

public class MdcTaskDecorator implements TaskDecorator {
    @NotNull
    @Override
    public Runnable decorate(@NotNull Runnable runnable) {
        Map<String, String> contextMap = MDC.getCopyOfContextMap();
        return () -> {
            try {
                // 传递已有TraceId或生成新ID
                if (contextMap != null) {
                    MDC.setContextMap(contextMap);
                } else {
                    TraceIdContext.ensureTraceIdExists();
                }
                runnable.run();
            } finally {
                TraceIdContext.clearTraceId();
            }
        };
    }
}